package org.exez.modules.visitor.util;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.google.api.client.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.exez.modules.visitor.dto.FileDocument;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;

@Slf4j
public class PdfToImageUtil {
    /**
     * base64字符串转换成图片
     *
     * @param imgStr
     * @param path
     * @return
     */
    public static String generateImage(String imgStr, String path) {

        String jpg = UUID.randomUUID().toString().replace("-", "") + ".jpg";
        path = path + jpg;
        if (imgStr == null) {
            return "";
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            File file = new File(path);

            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return jpg;
        } catch (Exception e) {
            return jpg;
        }
    }

    /**
     * 将图片转换成base64格式进行存储
     *
     * @param imgFile
     * @return
     */
    public static String encodeToString(String imgFile) throws IOException {
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(data));
    }


    public static void main(String[] args) {
        String base64 = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAQKADAAQAAAABAAAAQAAAAABGUUKwAAAEgUlEQVR4Ae1ZPWgUQRR+7y6EK4wW0UIhYgTBSkFNQEQ4fxDxp7CIndgq0cLCn+APh2I0WgQR1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